package com.bkhc.common.repository;

import com.bkhc.common.entity.Menus;
import com.bkhc.common.entity.Role;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Repository
public interface RoleRepository extends JpaRepository<Role,String> , JpaSpecificationExecutor<Role> {

    default Page<Role> findAll(Role role, Pageable pageable){
     return findAll(new Specification<Role>() {
         @Override
         public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
             List<Predicate> predicate = new ArrayList<>();
             if(!StringUtils.isEmpty(role.getRoleCode())){
                 predicate.add(criteriaBuilder.equal(root.get("RoleCode").as(String.class),role.getRoleCode()));
             }
             if(!StringUtils.isEmpty(role.getRoleName())){
                 predicate.add(criteriaBuilder.like(root.get("RoleName").as(String.class),"%"+role.getRoleName()+"%"));
             }

             Predicate[] pre = new Predicate[predicate.size()];

             return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
         }
     },pageable);


    };
    @Query("SELECT  COUNT(u.roleCode) FROM  Role u WHERE u.roleCode=?1 or u.roleName=?2 ")
    int find(String roleCode, String roleName);

    @Query("SELECT r FROM Role r where r.roleCode in (select ur.roleCode from UserRole ur where ur.userId=?1)")
    List<Role> findAllByUserId(String userId);

    @Query("SELECT r FROM Role r where r.roleCode in (select ur.roleCode from UserRole ur where ur.userId=?1 and ur.status=?2)")
    List<Role> findAllByUserIdAndStatus(String userId, int status);

    @Query("select r.roleCode from RoleApi r where r.apiCode = (select a.code from ApiInfo a where a.code=?1)")
    List<String> findRoleCode(String code);

    @Query("select m from Menus m where m.code in (select a.menusCode from RoleMenus a where a.roleCode=?1)")
    List<Menus> getRoleMenus(String roleCode);
}
